﻿using System;
using System.Windows;
using System.Windows.Interactivity;

namespace AccessControl.Wpf.Behaviors
{
	class ActualSizeInjectorBehavior : Behavior<FrameworkElement>
	{
		#region Fields

		private static readonly Type s_ThisType = typeof(ActualSizeInjectorBehavior);

		#endregion

		#region Dependency Properties

		public static readonly DependencyProperty ActualWidthProperty = DependencyProperty.Register(
			"ActualWidth",
			typeof(double),
			s_ThisType,
			new PropertyMetadata(0.00));

		public static readonly DependencyProperty ActualHeightProperty = DependencyProperty.Register(
			"ActualHeight",
			typeof(double),
			s_ThisType,
			new PropertyMetadata(0.00));

		#endregion

		#region Public Members

		public double ActualWidth
		{
			get { return (double)GetValue(ActualWidthProperty); }
			set { SetValue(ActualWidthProperty, value); }
		}
			
		public double ActualHeight
		{
			get { return (double)GetValue(ActualHeightProperty); }
			set { SetValue(ActualHeightProperty, value); }
		}

		#endregion

		#region Virtuals

		protected override void OnAttached()
		{
			/* First the base class */
			base.OnAttached();
			/* Set initials */
			ActualWidth = AssociatedObject.ActualWidth;
			ActualHeight = AssociatedObject.ActualHeight;
			/* Register to the size changed event */
			AssociatedObject.SizeChanged += (OnAssociatedObjectSizeChanged);
		}

		protected override void OnDetaching()
		{
			AssociatedObject.SizeChanged -= (OnAssociatedObjectSizeChanged);

			/* And the base class */
			base.OnDetaching();
		}

		#endregion

		#region Private Members

		void OnAssociatedObjectSizeChanged(object sender, SizeChangedEventArgs e)
		{
			ActualWidth = AssociatedObject.ActualWidth;
			ActualHeight = AssociatedObject.ActualHeight;
		}

		#endregion
	}
}
